<?php

namespace app\middleware;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
use app\extend\Client\StatisticClient;

class StatisticSQLByApp implements MiddlewareInterface
{
    public function process(Request $request, callable $next): Response
    {
        $response = $next($request);

        // SQL监控
        \think\facade\Db::listen(function ($sql, $runtime, $master) {
            if ($sql == 'select 1') return true;

            $ip      = request()->getRealIp(true) ?? '';
            $project = 'OwenWeb项目AppSQL';
            switch (true) {
                case is_numeric($runtime):
                    $transfer = $sql;
                    $cost     = $runtime;
                    break;
                case !is_numeric($runtime) && 'CONNECT' === substr($sql, 0, 7):
                    @preg_match("/UseTime:([0-9]+(\\.[0-9]+)?|[0-9]+(\\.[0-9]+))/", $sql, $result);
                    if (count($result) > 1) {
                        $transfer = substr($sql, strpos($sql, "s ] ") + 4);
                        $cost     = $result[1];
                    } else {
                        $transfer = $sql;;
                        $cost = 0;
                    }
                    break;
                default:
                    $transfer = $sql;;
                    $cost = 0;
                    break;
            }
            StatisticClient::report('', $project, $ip, $transfer, true, 1, json_encode([
                'sql'     => $sql,
                'runtime' => $cost . 's',
                'master'  => $master,
            ], 320), $cost);
        });

        return $response;
    }
}